<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<c:set var="contextPath" value="${pageContext.request.contextPath}"></c:set>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta charset=UTF-8"">
<title>进销存报表</title>
<link rel="stylesheet" href="${contextPath}/static/statistics/css/bootstrap.min.css" />
<link rel="stylesheet" href="${contextPath}/static/bootstrap/css/bootstrap-table.css" />
<link rel="stylesheet" href="${contextPath}/static/ace/assets/css/ace.css" />
<link rel="stylesheet" href="${contextPath}/static/bootstrap/css/bootstrap-select.css" />
<link rel="stylesheet" href="${contextPath}/static/statistics/css/bootstrap-datetimepicker.min.css">
<link rel="stylesheet" href="${contextPath}/static/ztree/css/zTreeStyle.css" />
<script src="${contextPath}/static/statistics/js/jquery.js"></script>
<script src="${contextPath}/static/statistics/js/bootstrap.min.js"></script>
<script src="${contextPath}/static/bootstrap/js/bootstrap-table.js"></script>
<script src="${contextPath}/static/bootstrap/js/bootstrap-table-zh-CN.js"></script>
<script src="${contextPath}/static/bootstrap/js/bootstrap-select.min.js"></script>
<script src="${contextPath}/static/bootstrap/js/defaults-zh_CN.min.js"></script>
<script src="${contextPath}/static/statistics/js/bootstrap-datetimepicker.min.js"></script>
<script src="${contextPath}/static/statistics/js/bootstrap-datetimepicker.fr.js"></script>
<script src="${contextPath}/static/statistics/js/bootstrap-datetimepicker.zh-CN.js"></script>
<script src="${contextPath}/static/ztree/js/jquery.ztree.core-3.5.js"></script>
<script src="${contextPath}/static/ztree/js/jquery.ztree.excheck-3.5.js"></script>
<script src="${contextPath}/static/util/dateutils.js"></script>
<script src="${contextPath}/static/util/protutils.js"></script>
<style type="text/css">
	input.combo-input{
		padding:7px 4px; 
	}
	.panel{
		margin-bottom:0px;	
	}
	.bs-actionsbox .btn-group button {
	    width: 45%;
	}
	.bootstrap-select:not([class*="col-"]):not([class*="form-control"]):not(.input-group-btn) {
	    width: 100%;
	}	
	.list-group-item{
		padding:5px 6px;
		font-size:11px;
	}
	#zoneCode .list-group .list-group-item:first-child{
		padding:7px 6px;
	}
	.panel-heading::after {
	    content: "";
	    display: block;
	    clear: both;
	}
	.caret{
		color:#ABBAC3;
	}
	.bootstrap-select > .btn{
		color:#ABBAC3 !important;
		background-color: #fff !important;
		text-shadow:none;
		border-width:1px;
	}
	.bootstrap-select > .btn:hover, .bootstrap-select > .btn:focus:hover, .bootstrap-select > .btn.focus:hover, .bootstrap-select > .btn:active:hover, .bootstrap-select > .btn:focus:active, .btn-default:focus:active, .open > .btn.dropdown-toggle, .open > .btn-default.dropdown-toggle, .open > .btn.dropdown-toggle:hover, .open > .btn-default.dropdown-toggle:hover, .open > .btn.dropdown-toggle:focus, .open > .btn-default.dropdown-toggle:focus, .open > .btn.dropdown-toggle.focus, .open > .btn-default.dropdown-toggle.focus, .open > .btn.dropdown-toggle:active, .open > .btn-default.dropdown-toggle:active {
	    background-color: #fff !important;
	    border-color: #ABBAC3;
	}
	.fixed-table-footer{
	    overflow: auto;
	}	
	.dropdown-header{
		cursor: pointer;
	}
</style>
</head>
<body>
 <div class="panel panel-default">
 			<div class="panel-heading">
 				<h3 class="panel-title pull-left" style="text-shadow:2px 1px 2px #ABBAC3">进销存报表</h3>
 				<h5 class="pull-right" id="timeCount" style="margin-top: 0;margin-bottom: 0;"></h5>
 			</div>
            <div class="panel-body">
                <form class="form-horizontal" class="form-inline" style="margin-bottom: 5px;"
				action="${contextPath}/ktcount/exportExcelPss" method="post" id="exportExcel">
					<input id="sortName" name="sortName" type="hidden" value="SUPPLIER_NAME" />
					<input id="sortOrder" name="sortOrder" type="hidden" value="asc">
                    <div class="form-group">
                        <div class="col-sm-2">
                            <input type="text" class="form-control" id="productName" name="productName" placeholder="请输入商品名称">
                        </div>
                        <div class="col-sm-2">
                        	<div class="input-group ">
                        		<input id="typeName" class="form-control" placeholder="选择商品类型" readonly/>
                        		<input id="typeId" name="prodType" type="hidden" />
                        		<input id="foreTypeName" name="foreTypeName" type="hidden" />
	                        	<span class="input-group-btn">
		                        	<div class="btn btn-primary btn-sm" onclick="javascript:$('#typeModal').modal('show');">
										选择
									</div>
	                        	</span>
                        	</div>
                        		                
						</div>
						<div class="col-sm-2">
                            <select class="form-control" id="supplierId"  multiple title="选择供应商名称" data-live-search="true" data-live-search-placeholder="搜索" data-actions-box="true" >
							</select>
							<input type="hidden" name="supplierId" id="supplierid" />
                        </div>
                        <div class="col-sm-2">
                            <input type="text" class="form-control" id="turnCreateDate" name="turnCreateDate" placeholder="查询开始时间" readonly />
                        </div>
                        <div class="col-sm-2">
							<input type="text" class="form-control" id="bindCreateDate" name="bindCreateDate" placeholder="查询结束时间" readonly />
                        </div>
                        
                    </div>
                    <div class="form-group">
                    	<div class="col-sm-2">
                            <input type="text" class="form-control" id="productCode" name="productCode" placeholder="请输入条码">
                        </div>
                        <div class="col-sm-2">
                            <input type="text" class="form-control" id="brandName" name="brandName" placeholder="请输入品牌">
                        </div>
                        <div class="col-sm-7">
                        <label class="radio-inline">
						       	 查询类型
						    </label>
                        	<label class="radio-inline">
						        <input type="radio" name="typeRadio" value="0" checked /> 商品汇总
						    </label>
							<label class="radio-inline">
						        <input type="radio" name="typeRadio" value="1" /> 大类汇总
						    </label>
						    <label class="radio-inline">
						        <input type="radio" name="typeRadio" value="3" /> 种类汇总
						    </label>						    
                        </div>
                       
                    </div>
                    <div class="form-group ">
                    	
                        <div class="col-sm-3">
                        	<div class="input-group ">
                        		<input id="areaName" name="areaName" class="form-control" placeholder="选择区域" readonly/>
                        		<input id="areaCode" name="areaCode" type="hidden" />
	                        	<span class="input-group-btn">
		                        	<div class="btn btn-primary btn-sm" onclick="javascript:$('#areaModal').modal('show');">
										选择
									</div>
	                        	</span>
                        	</div>
                        		                
						</div>
						<div class="col-sm-2">
                             <select class="selectpicker" multiple data-live-search="true" title="请选择店铺名称" data-live-search-placeholder="搜索" data-actions-box="true" id="shopName">
								<optgroup label="直营" data-icon="glyphicon-ok">
									<c:forEach items="${shopnames}" var="shopname">
										<c:if test="${shopname.shopType=='直营'}">
											<option value="${shopname.shopId}">${shopname.shopName}</option>
										</c:if>
									</c:forEach>
								</optgroup>
								<optgroup label="加盟" data-icon="glyphicon-ok">
									<c:forEach items="${shopnames}" var="shopname">
										<c:if test="${shopname.shopType=='加盟'}">
											<option value="${shopname.shopId}">${shopname.shopName}</option>
										</c:if>
									</c:forEach>
								</optgroup>
							</select>
							<input type="hidden" name="shopName" id="shopname" />
							<input type="hidden" name="shopIdName" id="shopIdName" />
                        </div>
                        <div class="col-sm-2">
                        	<label class="radio-inline">
						        <input type="radio" name="tbRadio" value="0" checked /> 包
						    </label>
							<label class="radio-inline">
						        <input type="radio" name="tbRadio" value="1" /> 条
						    </label>
                        </div>
                    	<div class="col-sm-1" style="text-align:left;">
                            <button type="button"  id="btn_query" class="btn btn-sm btn-info">查询</button>
                        </div>
                    </div>
                    <input type="hidden" id="colsTitles" name="colsTitles" />
                    <input type="hidden" id="colsFields" name="colsFields" />
                </form>
            </div>
        </div>      
 		<div id="toolbar" class="btn-group" style="margin-left:15px">
 			<button id="btn_refresh" type="button" class="btn btn-sm btn-warning">
                <span class="glyphicon glyphicon-refresh icon-refresh" aria-hidden="true"></span>刷新
            </button>
            <button onclick="exportExcel();" type="button" class="btn btn-sm btn-success">
                <span class="glyphicon glyphicon-file" aria-hidden="true"></span>导出
            </button>
            <button onclick="doPrint();" type="button" class="btn btn-sm btn-default">
                <span class="glyphicon glyphicon-print" aria-hidden="true"></span>打印
            </button>
            <button onclick="selectAll();" type="button" class="btn btn-sm btn-primary">
				全选
            </button>
            <button onclick="unSelectAll();" type="button" class="btn btn-sm btn-primary">
            	不选
            </button>

            <button type="button" class="btn btn-sm btn-success"
				onclick="javascript:window.history.go(-2);window.close();">
				<span class="glyphicon glyphicon-arrow-left" aria-hidden="true"></span>返回</button>
        </div>         
       <!--startprint--> 
		<table id="kt_pss"></table>
		<!--endprint-->
	<div id="areaModal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="areaModalLabel" aria-hidden="true">
		<div class="modal-dialog">
			<div class="modal-content">
				<div class="modal-header">
					<button type="button" class="close" data-dismiss="modal" aria-hidden="true">
						&times;
					</button>
					<h4 class="modal-title" id="areaModalLabel">
						选择区域
					</h4>
				</div>
				<div class="modal-body">
					<ul id="areatree" class="ztree">
					</ul>
				</div>
				<div class="modal-footer">
					<button type="button" class="btn btn-primary" onclick="javascript:selectedAreas()">
						确认
					</button>
					<button type="button" class="btn btn-default" data-dismiss="modal">取消
					</button>
				</div>
			</div><!-- /.modal-content -->
		</div><!-- /.modal -->
	</div>
			<div id="typeModal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="typeModalLabel" aria-hidden="true">
		<div class="modal-dialog">
			<div class="modal-content">
				<div class="modal-header">
					<button type="button" class="close" data-dismiss="modal" aria-hidden="true">
						&times;
					</button>
					<h4 class="modal-title" id="typeModalLabel">
						选择商品类型
					</h4>
				</div>
				<div class="modal-body">
					<ul id="typetree" class="ztree">
					</ul>
				</div>
				<div class="modal-footer">
					<button type="button" class="btn btn-primary" onclick="javascript:selectedTypes()">
						确认
					</button>
					<button type="button" class="btn btn-default" data-dismiss="modal">取消
					</button>
				</div>
			</div><!-- /.modal-content -->
		</div><!-- /.modal -->
		</div>
</body>
<script type="text/javascript">
var ISFIRSTLOAD = true;
$(function () {
	getProdType();
	getArea();
	timeCount();
	/*$('#shopName').selectpicker('selectAll');*/
	/*2018.12.10日修改-不选择所有门店*/
    $('#shopName').selectpicker('selectAll');
	$('#supplierId').selectpicker();
	initDatetimepicker([ "turnCreateDate", "bindCreateDate" ]);
	$(".dropdown-header").click(ddHeaderClick);
	$('#shopName').on('changed.bs.select',onSelectChange);
    //1.初始化Table
});
function getProdType(){
	$.ajax({
        url: '${contextPath}/ktcount/getProdTypes', //localhost:8080
        type: 'post',
        success: function (data) {
            var orginTypes = data.data;
            var setting = {
                    check: {
                        enable: true,
                        chkStyle: "checkbox",
                    },
                    data: {
                        simpleData: {
                            enable: true,
                            idKey: "TYPE_ID",
                            pIdKey: "PARENT_ID",
                            rootPId: ''
                        },
                        key: {
                            name: "TYPE_NAME"
                        },
                    }
                };
	            
                $.fn.zTree.init($("#typetree"), setting, orginTypes);
                selectedTypes();
                getSupplier();
                oTable.Init();
        },
        error: function (error) {
            alert(error)
        }
    })
}
function getArea(){
	$.ajax({
        url: '${contextPath}/ktcount/getAreas', //localhost:8080
        type: 'post',
        success: function (data) {
            var orginAreas = data.data;
            var setting = {
                    check: {
                        enable: true,
                        chkStyle: "checkbox",
                    },
                    data: {
                        simpleData: {
                            enable: true,
                            idKey: "ID",
                            pIdKey: "PARENT_ID",
                            rootPId: '',
                            areaCode:"ZONE_CODE"
                        },
                        key: {
                            name: "ZONE_NAME"
                        },
                    }
                };
                $.fn.zTree.init($("#areatree"), setting, orginAreas);
                
        },
        error: function (error) {
            alert(error)
        }
    })

}
function getSupplier(){
    var fenlei = $("#typeId").val();

    var fenleiAdd = fenlei.replace(/\'/g,'');

    $.ajax({
        url: '${contextPath}/ktcount/getSuppliers', //localhost:8080
        data:{"typeId":fenleiAdd},
        type: 'post',
        success: function (data) {
           	var data = data.data;
           	var html = "";
        	for(var i = 0;i < data.length;i++){
        		html +='<option value="'+data[i]["ID"]+'">'+data[i]["SUPPLIER_NAME"]+'</option>';
        	}

        	$("#supplierId").html(html);
        	$('#supplierId').selectpicker('refresh');
        	$("#supplierid").val("");
        },
        error: function (error) {
            alert(error)
        }
    })
}
function getShop(){
	$.ajax({
        url: '${contextPath}/ktcount/getShops', //localhost:8080
        data:{"zoneCode":$("#areaCode").val()},
        type: 'post',
        success: function (data) {
           	var data = data.data;
			var dstore = '<optgroup label="直营" data-icon="glyphicon-ok">',nstore = '<optgroup label="加盟" data-icon="glyphicon-ok">';
        	for(var i = 0;i < data.length;i++){
        		if('直营' == data[i]["shopType"]){
        			dstore +='<option value="'+data[i]["shopId"]+'">'+data[i]["shopName"]+'</option>';
        		}
				if('加盟' == data[i]["shopType"]){
					nstore +='<option value="'+data[i]["shopId"]+'">'+data[i]["shopName"]+'</option>';
        		}
        	}
        	dstore += '</optgroup>';
        	nstore += '</optgroup>';
        	$("#shopName").html(dstore+nstore);
        	$('#shopName').selectpicker('refresh');
        	$('#shopName').selectpicker('selectAll');
        },
        error: function (error) {
            alert(error)
        }
    })
}
var TableInit = function () {
    var oTableInit = new Object();
    //初始化Table
    function sumCol(data,colName){
    	var count = 0;
        for(var i=0;typeof(data)!="undefined" && i<data.length;i++){
            count+= parseFloat(data[i][colName])
    	}
    	return parseFloat(count.toFixed(2));
    }
    function removeJsonEle(OrgArr,filterArr,toFilterField){
    	var newArr = OrgArr;
    	for(j = 0,filterArrLen = filterArr.length;j < filterArrLen;j++){
	    	for(var i = 0,OrgArrLen = OrgArr.length;i < OrgArrLen;i++){
	    		if(OrgArr[i][toFilterField] == filterArr[j]){
	    			newArr = OrgArr.splice(i, 1); 
	    			break;
	    		}
	    	}
    	}
    	return OrgArr;
    }
    function triggerRemoveJsonEle(){
    	var OrgArr = [{
            field: 'ROWNUM_',
            title: '序号',
            myFooterFormatter:function(data){
            	return "合计";
            }
        },{
            field: 'ZONE_CODE',
            title: '区域编号',
            sortable: true,
            sortName:"s.ZONE_CODE"
        },{
            field: 'PRODUCT_CODE',
            title: '商品编号',
            sortable: true,
            sortName:"PRODUCT_CODE"
        },{
            field: 'PRODUCT_NAME',
            title: '商品名称',
            sortable: true,
            sortName:"PRODUCT_NAME"
        }, {
            field: 'TYPE_NAME',
            title: '品类名称',
            sortable: true,
            sortName:"TYPE_NAME"
        }, {
            field: 'BRAND_NAME',
            title: '品牌名称',
            sortable: true,
            sortName:"BRAND_NAME"
        }, {
            field: 'UNIT',
            title: '单位',
            sortable: true,
            sortName:"UNIT"
        }, {
            field: 'SPEC',
            title: '规格',
            sortable: true,
            sortName:"SPEC"
        }, {
            field: 'CST_PRICE',
            title: '进价(元)',
            sortable: true,
            sortName:"CST_PRICE"
        }, {
            field: 'TCST_PRICE',
            title: '进价(元)',
            sortable: true,
            sortName:"CST_PRICE"
        }, {
            field: 'RTL_PRICE',
            title: '售价(元)',
            sortable: true,
            sortName:"RTL_PRICE"
        }, {
            field: 'FSTOCK',
            title: '期初库存',
            sortable: true,
            sortName:"FSTOCK",
            myFooterFormatter:function(data){
            	var count = 0;
            	count += sumCol(data,"FSTOCK");
            	return this.title+": "+count;
            }
        }, {
            field: 'TFSTOCK',
            title: '期初库存',
            sortable: true,
            sortName:"FSTOCK",
            myFooterFormatter:function(data){
            	var count = 0;
            	count += sumCol(data,"TFSTOCK");
            	return this.title+": "+count;
            }
        }, {
            field: 'FST',
            title: '期初成本金额(元)',
            sortable: true,
            sortName:"FST",
            myFooterFormatter:function(data){
            	var count = 0;
            	count += sumCol(data,"FST");
            	return this.title+": "+count;
            }
        }, {
            field: 'FSR',
            title: '期初售价金额(元)',
            sortable: true,
            sortName:"FSR",
            myFooterFormatter:function(data){
            	var count = 0;
            	count += sumCol(data,"FSR");
            	return this.title+": "+count;
            }
        }, {
            field: 'QTT',
            title: '销售数量',
            sortable: true,
            sortName:"QTT",
            myFooterFormatter:function(data){
            	var count = 0;
            	count += sumCol(data,"QTT");
            	return this.title+": "+count;
            }
        }, {
            field: 'TQTT',
            title: '销售数量',
            sortable: true,
            sortName:"QTT",
            myFooterFormatter:function(data){
            	var count = 0;
            	count += sumCol(data,"TQTT");
            	return this.title+": "+count;
            }
        }, {
            field: 'QRJE',
            title: '销售金额(元)',
            sortable: true,
            sortName:"QRJE",
            myFooterFormatter:function(data){
            	var count = 0;
            	count += sumCol(data,"QRJE");
            	return this.title+": "+count;
            }
        }, {
            field: 'QRCB',
            title: '销售成本(元)',
            sortable: true,
            sortName:"QRCB",
            myFooterFormatter:function(data){
            	var count = 0;
            	count += sumCol(data,"QRCB");
            	return this.title+": "+count;
            }
        },  {
            field: 'QRC',
            title: '销售毛利(元)',
            sortable: true,
            sortName:"QRC",
            myFooterFormatter:function(data){
            	var count = 0;
            	count += sumCol(data,"QRC");
            	return this.title+": "+count;
            }
        }, {
            field: 'CQ',
            title: '采购数量',
            sortable: true,
            sortName:"CQ",
            myFooterFormatter:function(data){
            	var count = 0;
            	count += sumCol(data,"CQ");
            	return this.title+": "+count;
            }
        }, {
            field: 'TCQ',
            title: '采购数量',
            sortable: true,
            sortName:"CQ",
            myFooterFormatter:function(data){
            	var count = 0;
            	count += sumCol(data,"TCQ");
            	return this.title+": "+count;
            }
        }, {
            field: 'CAMT',
            title: '采购金额(元)',
            sortable: true,
            sortName:"CAMT",
            myFooterFormatter:function(data){
            	var count = 0;
            	count += sumCol(data,"CAMT");
            	return this.title+": "+count;
            }
        },{
            field: 'PFSL',
            title: '批发数量',
            sortable: true,
            sortName:"PFSL",
            myFooterFormatter:function(data){
            	var count = 0;
            	count += sumCol(data,"PFSL");
            	return this.title+": "+count;
            }
        }, {
            field: 'PFJE',
            title: '批发金额(元)',
            sortable: true,
            sortName:"PFJE",
            myFooterFormatter:function(data){
            	var count = 0;
            	count += sumCol(data,"PFJE");
            	return this.title+": "+count;
            }
        }, {
            field: 'YIQUANTITY',
            title: '移动入库数量',
            sortable: true,
            sortName:"YIQUANTITY",
            myFooterFormatter:function(data){
            	var count = 0;
            	count += sumCol(data,"YIQUANTITY");
            	return this.title+": "+count;
            }
        }, {
            field: 'TYIQUANTITY',
            title: '移动入库数量',
            sortable: true,
            sortName:"YIQUANTITY",
            myFooterFormatter:function(data){
            	var count = 0;
            	count += sumCol(data,"TYIQUANTITY");
            	return this.title+": "+count;
            }
        }, {
            field: 'YIQP',
            title: '移动入库金额',
            sortable: true,
            sortName:"YIQP",
            myFooterFormatter:function(data){
            	var count = 0;
            	count += sumCol(data,"YIQP");
            	return this.title+": "+count;
            }
        }, {
            field: 'IQUANTITY',
            title: '调入数量',
            sortable: true,
            sortName:"IQUANTITY",
            myFooterFormatter:function(data){
            	var count = 0;
            	count += sumCol(data,"IQUANTITY");
            	return this.title+": "+count;
            }
        }, {
            field: 'TIQUANTITY',
            title: '调入数量',
            sortable: true,
            sortName:"IQUANTITY",
            myFooterFormatter:function(data){
            	var count = 0;
            	count += sumCol(data,"TIQUANTITY");
            	return this.title+": "+count;
            }
        }, {
            field: 'IQP',
            title: '调入金额',
            sortable: true,
            sortName:"IQP",
            myFooterFormatter:function(data){
            	var count = 0;
            	count += sumCol(data,"IQP");
            	return this.title+": "+count;
            }
        }, {
            field: 'OQUANTITY',
            title: '调出数量',
            sortable: true,
            sortName:"OQUANTITY",
            myFooterFormatter:function(data){
            	var count = 0;
            	count += sumCol(data,"OQUANTITY");
            	return this.title+": "+count;
            }
        }, {
            field: 'TOQUANTITY',
            title: '调出数量',
            sortable: true,
            sortName:"OQUANTITY",
            myFooterFormatter:function(data){
            	var count = 0;
            	count += sumCol(data,"TOQUANTITY");
            	return this.title+": "+count;
            }
        }, {
            field: 'OQP',
            title: '调出金额',
            sortable: true,
            sortName:"OQP",
            myFooterFormatter:function(data){
            	var count = 0;
            	count += sumCol(data,"OQP");
            	return this.title+": "+count;
            }
        },{
            field: 'TQUANTITY',
            title: '直配退货数量',
            sortable: true,
            sortName:"TQUANTITY",
            myFooterFormatter:function(data){
            	var count = 0;
            	count += sumCol(data,"TQUANTITY");
            	return this.title+": "+count;
            }
        },{
            field: 'TTQUANTITY',
            title: '直配退货数量',
            sortable: true,
            sortName:"TQUANTITY",
            myFooterFormatter:function(data){
            	var count = 0;
            	count += sumCol(data,"TTQUANTITY");
            	return this.title+": "+count;
            }
        },{
            field: 'TQJE',
            title: '直配退货金额',
            sortable: true,
            sortName:"TQJE",
            myFooterFormatter:function(data){
            	var count = 0;
            	count += sumCol(data,"TQJE");
            	return this.title+": "+count;
            }
        }, {
            field: 'LSTOCK',
            title: '结存库存',
            sortable: true,
            sortName:"LSTOCK",
            myFooterFormatter:function(data){
            	var count = 0;
            	count += sumCol(data,"LSTOCK");
            	return this.title+": "+count;
            }
        }, {
            field: 'TLSTOCK',
            title: '结存库存',
            sortable: true,
            sortName:"LSTOCK",
            myFooterFormatter:function(data){
            	var count = 0;
            	count += sumCol(data,"TLSTOCK");
            	return this.title+": "+count;
            }
        }, {
            field: 'LST',
            title: '结存成本金额(元)',
            sortable: true,
            sortName:"LST",
            myFooterFormatter:function(data){
            	var count = 0;
            	count += sumCol(data,"LST");
            	return this.title+": "+count;
            }
        }, {
            field: 'LSR',
            title: '结存售价金额(元)',
            sortable: true,
            sortName:"LSR",
            myFooterFormatter:function(data){
            	var count = 0;
            	count += sumCol(data,"LSR");
            	return this.title+": "+count;
            }
        },  {
            field: 'BHSJCJE',
            title: '不含税结存金额(元)',
            sortable: true,
            sortName:"BHSJCJE",
            myFooterFormatter:function(data){
            	var count = 0;
            	count += sumCol(data,"BHSJCJE");
            	return this.title+": "+count;
            }
        },  {
            field: 'BHSCGJE',
            title: '不含税采购金额(元)',
            sortable: true,
            sortName:"BHSCGJE",
            myFooterFormatter:function(data){
            	var count = 0;
            	count += sumCol(data,"BHSCGJE");
            	return this.title+": "+count;
            }
        },  {
            field: 'DCCBJE',
            title: '调出成本金额(元)',
            sortable: true,
            sortName:"DCCBJE",
            myFooterFormatter:function(data){
            	var count = 0;
            	count += sumCol(data,"DCCBJE");
            	return this.title+": "+count;
            }
        },  {
            field: 'DRCBJE',
            title: '调入成本金额(元)',
            sortable: true,
            sortName:"DRCBJE",
            myFooterFormatter:function(data){
            	var count = 0;
            	count += sumCol(data,"DRCBJE");
            	return this.title+": "+count;
            }
        },  {
            field: 'QTJE',
            title: '其他成本金额(元)',
            sortable: true,
            sortName:"QTJE",
            myFooterFormatter:function(data){
            	var count = 0;
            	count += sumCol(data,"QTJE");
            	return this.title+": "+count;
            }
        },  {
            field: 'CBCYJE',
            title: '成本差异金额(元)',
            sortable: true,
            sortName:"CBCYJE",
            myFooterFormatter:function(data){
            	var count = 0;
            	count += sumCol(data,"CBCYJE");
            	return this.title+": "+count;
            }
        },  {
            field: 'XSKBJE',
            title: '销售扣补金额(元)',
            sortable: true,
            sortName:"XSKBJE",
            myFooterFormatter:function(data){
            	var count = 0;
            	count += sumCol(data,"XSKBJE");
            	return this.title+": "+count;
            }
        }]
    	var searchType = $("input[name='typeRadio']:checked").val();
    	var tbType = $("input[name='tbRadio']:checked").val();
    	var tbcols = [];
    	if(tbType == 0)
    		tbcols = ['TCST_PRICE','TLSTOCK','TTQUANTITY','TOQUANTITY','TIQUANTITY','TYIQUANTITY','TCQ','TQTT','TFSTOCK'];
    	else
    		tbcols = ['CST_PRICE','LSTOCK','TQUANTITY','OQUANTITY','IQUANTITY','YIQUANTITY','CQ','QTT','FSTOCK'];
    	if(searchType == 0)
    		return removeJsonEle(OrgArr,[].concat(tbcols),"field")
    	else if(searchType == 1 || searchType == 3)
    		return removeJsonEle(OrgArr,["ZONE_CODE","PRODUCT_CODE","PRODUCT_NAME","BRAND_NAME","UNIT","SPEC","CST_PRICE","RTL_PRICE"].concat(tbcols),"field")

    }
    function getFieldIndex(fieldName){
    	var orgArr = triggerRemoveJsonEle();
    	for(var i = 0,orgArrLen = orgArr.length;i < orgArrLen;i++){
    		if(fieldName == orgArr[i]["field"]){
    			return i;
    		}
    	}
    }
    oTableInit.Init = function () {
    	if($("#btn_query").hasClass("btn-info")){
    		$("#btn_query").removeClass("btn-info").addClass("btn-default");
		}
        $('#kt_pss').bootstrapTable({
            url: '${contextPath}/ktcount/getktPss',         //请求后台的URL（*）
            method: 'POST',                      //请求方式（*）
            toolbar: '#toolbar',                //工具按钮用哪个容器
            striped: true,                      //是否显示行间隔色
            cache: false,                       //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
            pagination: true,                   //是否显示分页（*）
            sortable: true,                     //是否启用排序
            sortName: "BRAND_NAME",
            sortOrder: "asc",                   //排序方式
            queryParams: oTableInit.queryParams,//传递参数（*）
            sidePagination: "server",           //分页方式：client客户端分页，server服务端分页（*）
            pageNumber:1,                       //初始化加载第一页，默认第一页
            pageSize: 10000,                       //每页的记录行数（*）
            pageList: [10, 50, 100,10000],        //可供选择的每页的行数（*）
            strictSearch: true,
            showColumns: true,                  //是否显示所有的列
            showHeader:true,
            minimumCountColumns: 2,             //最少允许的列数
            clickToSelect: true,                //是否启用点击选中行
            height: 500,                        //行高，如果没有设置height属性，表格自动根据记录条数觉得表格高度
            uniqueId: "ID",                     //每一行的唯一标识，一般为主键列
            showToggle:true,                    //是否显示详细视图和列表视图的切换按钮
            cardView: false,                    //是否显示详细视图
            detailView: false,                   //是否显示父子表
            showFooter:true,
            columns: triggerRemoveJsonEle() ,
            contentType : "application/x-www-form-urlencoded",
            onLoadSuccess: function(data){
            	$("#btn_query").removeClass("btn-default").addClass("btn-info");
            	if(ISFIRSTLOAD){
            		var searchType = $("input[name='typeRadio']:checked").val();
                	var iarr = [];
                	if(searchType == 0){
                		iarr=[1,4,5,11,12,15,16,19,20,24,26,30,31,32,33,34,35,36,37,38]
                	}else{
                		iarr=[3,4,7,8,11,12,14,16,18,22,23,24,25,26,27,28,29,30]
                	}
                	var visibleCols = $('#kt_pss').bootstrapTable('getVisibleColumns');
                	for(var i = 0,iarrLen = iarr.length;i<iarrLen;i++){
                		$('#kt_pss').bootstrapTable('hideColumn', visibleCols[iarr[i]]["field"]);
                		toggleFootrowTd(visibleCols[iarr[i]]["fieldIndex"],false)
                	}
                	ISFIRSTLOAD = false;
            	} 
            	refreshFooterData(data.rows);
            },
            onColumnSwitch:function(field, checked){
            	var fieldIndex = getFieldIndex(field);
            	toggleFootrowTd(fieldIndex,checked)
            }
        });
    };
    oTableInit.queryParams = function (params) {
    	var shopName = $("#shopName").val() == null ? "\'\'":$("#shopName").val().join(",");
    	var supplierIds = $("#supplierId").val(),
    		supplierId = "";
    	if(supplierIds != null){
    		for(var i=0;i<supplierIds.length;i++){
    			supplierId +="\'"+supplierIds[i]+"\',"
    		}
    		supplierId = supplierId.substring(0,supplierId.length-1)
    	}
    	var searchType = $("input[name='typeRadio']:checked").val();
    	if(searchType != 0){
    		params.sort = params.sort == "BRAND_NAME" ? "":"BRAND_NAME";
    	}
    	$("#sortName").val(params.sort);
    	$("#sortOrder").val(params.order);
    	var temp = {   //这里的键的名字和控制器的变量名必须一直，这边改动，控制器也需要改成一样的
            limit: params.limit,   //页面大小
            offset: params.offset,  //页码
            sortName: params.sort,
            sortOrder: params.order,
            shopName : shopName,
	    	prodType : $("#typeId").val().trim(),
	    	productName : $("#productName").val().trim(),
	    	turnCreateDate :$("#turnCreateDate").val().trim(),
	    	bindCreateDate : $("#bindCreateDate").val().trim(),
	    	productCode : $("#productCode").val().trim(),
	    	brandName : $("#brandName").val().trim(),
	    	supplierId : supplierId.replace(/\'/g,''),
	    	typeRadio: searchType
        };
        return temp;
    };
    return oTableInit;
}
var oTable = new TableInit();
$("#btn_refresh").bind('click',function(){
	if($("#btn_query").hasClass("btn-default")){
		return;
	}
	$("#btn_query").removeClass("btn-info").addClass("btn-default");
	$('#shopName').selectpicker('selectAll');
	$('#supplierId').selectpicker();
	$("#productName").val("");
	$("#productCode").val("");
	$("#turnCreateDate").val(trans2FormatDate(new Date()));
	$("#bindCreateDate").val(trans2FormatDate(new Date()));
	$("#areaCode").val("");
	$("#supplierid").val("");
	$("#areaName").val("");
	//$('#zoneCode').treeview('clearSearch');
	$('#kt_pss').bootstrapTable('refresh', { url: '${contextPath}/ktcount/getktPss'});
})
$("#btn_query").bind("click",function(){
	if($("#btn_query").hasClass("btn-default")){
		return;
	}
	$("#btn_query").removeClass("btn-info").addClass("btn-default");
	if(ISFIRSTLOAD){
		$("#kt_pss").bootstrapTable('destroy');
		oTable.Init();
		return;
	}
	$('#kt_pss').bootstrapTable('refresh', { url: '${contextPath}/ktcount/getktPss'});
})
$("input[name='typeRadio'],input[name='tbRadio']").change(function(){
	ISFIRSTLOAD = true;
})
function initDatetimepicker(arr) {
	arr.forEach(function(item, index, input) {
		$('#' + item).datetimepicker({
			language : 'zh-CN',
			weekStart : 1,
			todayBtn : 1,
			todayHighlight : 1,
			startView : 3,
			forceParse : 0,
			showMeridian : 1,
			format : "yyyy-mm-dd",
			autoclose : true,
			minView : "month",
			initialDate:trans2FormatDate(new Date())
		}).on('changeDate', function(ev){
		    var idVal = $(this).attr("id");
		    var date = ev.date;
		    if(idVal == "turnCreateDate"){
		    	$("#turnCreateDate").val(date.getFullYear()+"-"+(date.getMonth()+1)+"-"+date.getDate()+" 00:00:00")
		    }else{
		    	$("#bindCreateDate").val(date.getFullYear()+"-"+(date.getMonth()+1)+"-"+date.getDate()+" 23:59:59")
		    }
		});;
		$('#' + item).datetimepicker('setEndDate', trans2FormatDate(new Date()));
	})
	$('#turnCreateDate').val(trans2FormatDate(new Date(),false)+" 00:00:00")
	$('#bindCreateDate').val(trans2FormatDate(new Date(),false)+" 23:59:59")
}
function toggleFootrowTd(fieldIndex,checked){
	var td = $(".fixed-table-footer").find("td").get(fieldIndex);
	if(!checked)
		td.style.display = "none";
	else{
		td.style.display = "";
	}
}
function selectAll(){
	var hiddenCols = $('#kt_pss').bootstrapTable('getHiddenColumns');
	for(var i = 0,hiddenColsLen = hiddenCols.length;i<hiddenColsLen;i++){
		$('#kt_pss').bootstrapTable('showColumn', hiddenCols[i]["field"]);
		toggleFootrowTd(hiddenCols[i]["fieldIndex"],true)
	}
}
function unSelectAll(){
	var visibleCols = $('#kt_pss').bootstrapTable('getVisibleColumns');
	for(var i = 1,visibleColsLen = visibleCols.length;i<visibleColsLen;i++){
		$('#kt_pss').bootstrapTable('hideColumn', visibleCols[i]["field"]);
		toggleFootrowTd(visibleCols[i]["fieldIndex"],false)
	}
}
function refreshFooterData(data){
	var visibleCols = $('#kt_pss').bootstrapTable('getVisibleColumns');
	var tds = $(".fixed-table-footer").find("td");
	for(i in visibleCols){
		if(visibleCols[i].hasOwnProperty("myFooterFormatter")){
			$(tds.get(visibleCols[i]["fieldIndex"])).find(".th-inner").html(visibleCols[i]["myFooterFormatter"].call(visibleCols[i],data))
		}
	}
}
function trans2FormatDate(date,isMonth){
	date.setDate(date.getDate() - 1);
	isMonth && date.setMonth(date.getMonth()-1);
	return date.getFullYear()+"-"+(date.getMonth()+1)+"-"+date.getDate()
}
function selectedAreas(){
	 $("#areaModal").modal('hide')
     var zTree = $.fn.zTree.getZTreeObj("areatree");
     var nodes = zTree.getCheckedNodes();
     var areaNameVal = "",areaCodeVal = "";
     for(var i = 0,nodesLen = nodes.length;i < nodesLen;i++){
    	 if(!nodes[i]["isParent"]){
	    	 areaNameVal += nodes[i]["ZONE_NAME"]+",";
	    	 areaCodeVal += nodes[i]["ZONE_CODE"]+",";
    	 }
     }
     if(nodes.length > 0){
	    areaNameVal = areaNameVal.substring(0,areaNameVal.length-1);
	    areaCodeVal = areaCodeVal.substring(0,areaCodeVal.length-1);

     }
     $("#areaName").val(areaNameVal)
     $("#areaCode").val(areaCodeVal)
     getShop();
}
function selectedTypes(){
	 $("#typeModal").modal('hide')
    var zTree = $.fn.zTree.getZTreeObj("typetree");
    var nodes = zTree.getCheckedNodes();
    var typeNameVal = "",typeIdVal = "",foreTypeNameVal = "";
    for(var i = 0,nodesLen = nodes.length;i < nodesLen;i++){
   	 if(!nodes[i]["isParent"]){
	    	 typeNameVal += nodes[i]["TYPE_NAME"]+",";
	    	 typeIdVal += nodes[i]["TYPE_ID"]+",";
   	 }
   	 if(nodes[i]["level"] == 0){
   		 foreTypeNameVal += nodes[i]["TYPE_NAME"]+",";
   	 }
    }
    if(nodes.length > 0){
   	 typeNameVal = typeNameVal.substring(0,typeNameVal.length-1);
   	 typeIdVal = typeIdVal.substring(0,typeIdVal.length-1);
   	 foreTypeNameVal = foreTypeNameVal.substring(0,foreTypeNameVal.length-1);
    }
    $("#typeName").val(typeNameVal)
    $("#typeId").val(typeIdVal)
    $("#foreTypeName").val(foreTypeNameVal)
    getSupplier();
}
var exportExcel = function() {
	var shopName = $("#shopName").val() == null ? "\'\'":$("#shopName").val().join(",");
	$("#shopname").val(shopName);
	var shopIdName = $("[data-id='shopName']").attr("title");
	if(shopIdName.indexOf(",") == -1 && shopIdName!="选择商店名称"){
		$("#shopIdName").val(shopIdName);
	}
	var supplierIds = $("#supplierId").val(),
		supplierId = "";
	if(supplierIds != null){
		for(var i=0;i<supplierIds.length;i++){
			supplierId +="\'"+supplierIds[i]+"\',"
		}
		supplierId = supplierId.substring(0,supplierId.length-1)
	}
	$("#supplierid").val(supplierId)
	var visibleCols = $('#kt_pss').bootstrapTable('getVisibleColumns');
	var fields = "",titles = "";
	for(var i = 0,visibleColsLen = visibleCols.length;i<visibleColsLen;i++){
		fields += visibleCols[i]["field"]+",";
		titles += visibleCols[i]["title"]+",";
	}
	$("#colsTitles").val(titles.substring(0,titles.length-1));
	$("#colsFields").val(fields.substring(0,fields.length-1));
	$("#exportExcel").submit();

}
function ddHeaderClick(e){
	var $span = $(this).children("span:first-child");
	var idVal = $(this).parent().parent().next().attr("id");
	var allSelected = $("#"+idVal).val() || [];
	var index = $(this).attr("data-optgroup")-1;
	var $groupOption = $("#"+idVal).find('optgroup').eq(index).find("option");
	$groupOption.each(function(index,element){
		if($span.hasClass("glyphicon-ok")){
			allSelected.remove($(this).val());
		}else{
			allSelected.push($(this).val())
		}
	})
	if($span.hasClass("glyphicon-ok")){
		$span.removeClass("glyphicon-ok")
	}else{
		$span.addClass("glyphicon-ok")
	}
	$("#"+idVal).selectpicker('val',allSelected)
}
function onSelectChange(e){
	var idVal = $(this).attr("id");
	var $ddHeader = $("#"+idVal).prev().find(".dropdown-header");
	var $optgroup = $(this).find("optgroup");
	$optgroup.each(function(index,element){
		var optionLen = $(this).find('option:selected').length;
		var $span = $ddHeader.eq(index).children("span:first-child");
		if(optionLen > 0){
			if(!$span.hasClass("glyphicon-ok")){
				$span.addClass("glyphicon-ok")
			}
		}else{
			if($span.hasClass("glyphicon-ok")){
				$span.removeClass("glyphicon-ok")
			}
		}
	})
}
function doPrint() {
    bdhtml=window.document.body.innerHTML;
    sprnstr="<!--startprint-->";
    eprnstr="<!--endprint-->";
    prnhtml=bdhtml.substr(bdhtml.indexOf(sprnstr)+17);
    prnhtml=prnhtml.substring(0,prnhtml.indexOf(eprnstr));
    window.document.body.innerHTML=prnhtml;
    window.print();
    window.location.reload(); //刷新当前页面
}
function timeCount(){
	var oDateUtil = new DateUtil();
	setInterval(function(){
		var date = new Date();
		var formatDate = oDateUtil.formatDate(date,"yyyy-MM-dd hh:mm:ss",true);
		$("#timeCount").html(formatDate)
	},1000)
}
</script>
</html>